<?php
namespace Resolution;

/**
 * Created by PhpStorm.
 * User: Mr.Li<LHB2002@qq.com>
 * Date: 2017-09-28
 * Time: 11:32
 */
class ImageGD2
{
    private $style;
    private $source_image_path;
    private $cache_image_path;
    public function __construct($style)
    {
        if (!extension_loaded('gd')) {
            trigger_error('你必须启用 GD 扩展', E_USER_WARNING);
            throw new ResolutionException('你必须启用 GD 扩展');
        }
        $this->style = $style;
    }

    /**
     * 设置源图片
     * @author Mr.Li<lhb2002@qq.com>
     */
    public function setSourceImagePath($path ){
        $this->source_image_path = $path;
        return $this;
    }

    /**
     * 设置缓存图片
     * @author Mr.Li<lhb2002@qq.com>
     */
    public function setCacheImagePath($path ){
        $this->cache_image_path = $path;
        return $this;
    }

    /**
     * 生成图片
     * @author Mr.Li<lhb2002@qq.com>
     */
    public function generate(){

        //判断缓存文件是否存在
        if(file_exists($this->cache_image_path)) {
            return $this->cache_image_path;
        }

        $source_size = filesize($this->source_image_path) ;
        //检查忽略文件大小

        if($this->style->ignore && $source_size < $this->style->ignore ){
            return $this->source_image_path;
        }


        $source_image = $this->loadSourceImage();

        if($this->isGifAnimation()){
            return $this->source_image_path;
        }

        //设置原图尺寸
        $this->style->setSource($source_image['width'], $source_image['height']);

        $cache_image        =   imagecreatetruecolor($this->style->width,$this->style->height);

        //重构图片尺寸
        imagecopyresampled($cache_image, $source_image['resource'], 0, 0, 0, 0, $this->style->width, $this->style->height, $source_image['width'], $source_image['height']);
        //销毁原图
        imagedestroy($source_image['resource']);

        $function = $this->getImageFunction('image',$source_image['extension']);
        $function($cache_image,$this->cache_image_path);
        imagedestroy($cache_image);

        //生成图片大小，大于原图时，使用原图输出
        if(filesize($this->cache_image_path) > $source_size){
            copy($this->source_image_path,$this->cache_image_path);
        }

        return $this->cache_image_path ;
    }

    /**
     * 判断图片是否为gif动画
     * @param $image
     * @return bool
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function isGifAnimation(){
        $extension = strtolower(pathinfo($this->source_image_path, PATHINFO_EXTENSION));
        if('gif'==$extension){
            $content= file_get_contents($this->source_image_path);
            if(preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$content)){
                return true;
            }else{
                return false;
            }
        }
        else{
            return false;
        }
    }

     /**
     * 加载图片
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function loadSourceImage(){

        $extension = strtolower(pathinfo($this->source_image_path, PATHINFO_EXTENSION));

        $funciton = $this->getImageFunction('imagecreatefrom',$extension);

        $source_image = @$funciton($this->source_image_path);
        if($source_image){
            list($width,$height)   = GetImageSize($this->source_image_path);
            return array(
                'extension' =>  $extension,
                'width'     =>  $width,
                'height'    =>  $height,
                'resource'  =>  $source_image
            );
        }
        else{
            throw new ResolutionException('加载源图片失败\n'. $this->source_image_path);
        }
    }

    /**
     * 获取指定的函数
     * @param $function 函数前缀
     * @param $extension 根据扩展名获取函数后缀
     * @return string
     * @throws ResolutionException
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function getImageFunction($function, $extension){
        if(!in_array($function,array('imagecreatefrom','image'))){
            return $function;
        }
        $extensions = array(
            'bmp',
            'gd2',
            'gd',
            'gif',
            'jpeg',
            'png',
            'wbmp',
            'webp',
            'xbm',
            'xpm'
        );
        //替换jpg扩展名为jpeg类型
        if('jpg' == $extension){
            $extension = 'jpeg';
        }

        if(in_array($extension,$extensions)){
            return $function.$extension;
        }
        else{
            throw new ResolutionException('错误的函数请求' . $function . $extension);
        }
    }

}